package com.kaihui.module_web.jsinterface


import android.content.ClipData
import android.content.ClipboardManager
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Environment
import android.os.Handler
import android.os.Looper
import android.provider.MediaStore
import android.webkit.JavascriptInterface
import androidx.core.content.ContextCompat.startActivity
import androidx.core.content.FileProvider
import androidx.test.internal.runner.junit4.statement.UiThreadStatement.runOnUiThread
import cn.org.bjca.signet.component.core.bean.results.BioStatusResult
import cn.org.bjca.signet.component.core.bean.results.GetCertResult
import cn.org.bjca.signet.component.core.bean.results.SignImageResult
import cn.org.bjca.signet.component.core.bean.results.SignetBaseResult
import cn.org.bjca.signet.component.core.enums.CertType
import cn.org.bjca.signet.component.core.enums.IdCardType
import cn.org.bjca.signet.component.core.enums.SetFingerOperType
import cn.org.bjca.signet.component.core.enums.SetSignImgType
import cn.org.bjca.signet.coss.interfaces.CossGetUserStateCallBack
import cn.org.bjca.signet.coss.interfaces.CossReqCertCallBack

import cn.org.bjca.unifysdk.bean.UserListResult
import cn.org.bjca.unifysdk.signet.bean.CertResult
import cn.org.bjca.unifysdk.signet.bean.ReqCertResult
import cn.org.bjca.unifysdk.signet.bean.SignetConfig
import cn.org.bjca.unifysdk.signet.callback.ReqCertCallBack
import com.google.gson.Gson
import com.just.agentweb.AgentWeb
import com.kaihui.lib_base.data.local.IpManager
import com.kaihui.lib_base.utils.LogUtil
import com.kaihui.lib_base.utils.ToastUtil
import com.kaihui.module_web.ui.web.WebActivity
import kotlinx.coroutines.launch
import java.io.File
import java.io.IOException
import java.text.SimpleDateFormat
import java.util.Date


class AndroidInterface(
    private val agentWeb: AgentWeb,
    private val activity: WebActivity,
) {
    private val deliver = Handler(Looper.getMainLooper())


    @JavascriptInterface
    fun takePhoto() {
        ToastUtil.showShort(activity, "调用了takePhoto")
        LogUtil.e("H5交互:takePhoto")

        try {
            // 1. 创建File对象，用于存储拍照后的图片
            val outputImage = File(
                Environment.getExternalStoragePublicDirectory(
                    Environment.DIRECTORY_DCIM
                ), "Camera"
            )
            if (!outputImage.exists()) {
                if (!outputImage.mkdirs()) {
                    LogUtil.e("failed to create directory")
                }
            }
            val timeStamp: String = SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())
            val mediaFile = File(
                outputImage.path + File.separator +
                        "IMG_" + timeStamp + ".jpg"
            )

            activity.imageUri = FileProvider.getUriForFile(
                activity,
                "androidx.core.content.FileProvider",//定义唯一标识，关联后面的内容提供器
                mediaFile
            )
            // 3. 启动相机程序
            val intent = Intent("android.media.action.IMAGE_CAPTURE")
            intent.putExtra(MediaStore.EXTRA_OUTPUT, activity.imageUri)
            activity.startActivityForResult(intent, WebActivity.TAKE_PHOTO)
        } catch (e: IOException) {
            e.printStackTrace()
        }

    }


    @JavascriptInterface
    fun scan() {
        ToastUtil.showShort(activity, "调用了scan")
    }

    // 方法: 退出app
    @JavascriptInterface
    fun exitApp() {
        LogUtil.e("调用了quit()")
        activity.scope.launch { activity.finishAffinity() }

    }

    // 方法1: 重新加载URL
    @JavascriptInterface
    fun reload() {
        LogUtil.e("调用了reload(url):${agentWeb.webCreator.webView.url}")
        activity.scope.launch { agentWeb.urlLoader.reload() }

    }

    // 方法2: 重新加载指定URL
    @JavascriptInterface
    fun reload(url: String) {
        LogUtil.e("调用了reload(url):$url")
        activity.scope.launch { agentWeb.urlLoader.loadUrl(url) }

    }

    @JavascriptInterface
    fun goHome() {
        LogUtil.e("调用了goHome()")
        activity.scope.launch { activity.goHome() }
//        activity.mainHandler.post { }
    }

    /**
     * 方法1: 判断 WebView 是否可以返回
     */
    @JavascriptInterface
    fun canGoBack(): Boolean {
        return activity.backHelper?.canGoBack() == true
    }

    /**
     * 执行返回操作
     */
    @JavascriptInterface
    fun goBack() {
        activity.scope.launch { activity.backHelper?.goBack() }

    }


    @JavascriptInterface
    fun openPhoto() {
        ToastUtil.showShort(activity, "调用了openPhoto")
        val intent = Intent(Intent.ACTION_PICK, null)
        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        activity.startActivityForResult(intent, WebActivity.CHOOSE_PHOTO)
    }

    @JavascriptInterface
    fun downloadByBrowser(url: String) {
        ToastUtil.showShort(activity, "调用了downloadByBrowser")
        val intent = Intent(Intent.ACTION_VIEW)
        intent.addCategory(Intent.CATEGORY_BROWSABLE)
        intent.setData(Uri.parse(url))
        startActivity(activity.applicationContext, intent, null)
    }

    /**
     * 复制到剪贴板
     */
    @JavascriptInterface
    fun copyToClipboard(text: String) {
        try {
            val clipboard = activity.getSystemService(Context.CLIPBOARD_SERVICE) as ClipboardManager
            val clip = ClipData.newPlainText("text", text)
            clipboard.setPrimaryClip(clip)
            ToastUtil.showShort(activity, "已复制到剪切板")
        } catch (e: Exception) {
            e.printStackTrace()
            ToastUtil.showShort(activity, "复制失败")

        }
    }

    @JavascriptInterface
    fun initConfig(url: String, appId: String) {
        ToastUtil.showShort(activity, "initConfig")
        val signetConfig = SignetConfig()

        signetConfig.servUrl = url
        signetConfig.appId = appId
        activity.signetBaseResult = activity.signetApi?.initConfig(activity, signetConfig)
        LogUtil.e("signetBaseResult==" + activity.signetBaseResult)
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "reqCert",
            Gson().toJson(activity.signetBaseResult).toString()
        )

    }


    @JavascriptInterface
    fun reqCert(authCode: String, pin: String) {
        ToastUtil.showShort(activity, "调用了reqCert")
        activity.signetApi?.reqCert(
            activity, authCode, pin
        ) { p0 ->
            LogUtil.e(" ReqCertResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "reqCert",
                Gson().toJson(p0).toString()
            )
        }
    }


    @JavascriptInterface
    fun qrReqCert(pin: String) {

        ToastUtil.showShort(activity, "调用了qrReqCert")
        activity.signetApi?.qrReqCert(activity, pin, object : ReqCertCallBack {
            override fun onReqCert(p0: ReqCertResult?) {
                LogUtil.e(" ReqCertResult==" + Gson().toJson(p0).toString())
                agentWeb.jsAccessEntrace.quickCallJs(
                    "jsFunction",
                    "qrReqCert",
                    Gson().toJson(p0).toString()
                )
            }
        })
    }

    @JavascriptInterface
    fun findBackUser() {
        ToastUtil.showShort(activity, "调用了findBackUser")
        activity.signetApi?.findBackUser(activity) { p0 ->
            LogUtil.e("  FindBackUserResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "findBackUser",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun findbackUserInfo(name: String, idCardNumber: String, idCardType: String, pin: String) {
        ToastUtil.showShort(activity, "调用了findbackUserInfo")
        val status = IdCardType.values().find { it.name == idCardType }
        if (status != null) {
            activity.signetApi?.findbackUserInfo(activity, name, idCardNumber, status, pin) { p0 ->
                LogUtil.e("FindBackUserResult==" + Gson().toJson(p0).toString())
                agentWeb.jsAccessEntrace.quickCallJs(
                    "jsFunction",
                    "findbackUserInfo",
                    Gson().toJson(p0).toString()
                )
            }
        } else {
            ToastUtil.showShort(activity, "未找到$idCardType")
        }

    }

    @JavascriptInterface
    fun selfRegister() {
        ToastUtil.showShort(activity, "调用了selfRegister")
        activity.signetApi?.selfRegister(activity) { p0 ->
            LogUtil.e(" ReqCertResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "selfRegister",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun signData(
        msspID: String,
        signJobId: String,
        pin: String,
        isBackPin: Boolean,
    ) {
        ToastUtil.showShort(activity, "调用了signData")
        activity.signetApi?.signData(activity, msspID, signJobId, pin, isBackPin) { p0 ->
            LogUtil.e("  SignDataResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "signData",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun qrSignData(
        msspID: String,
        pin: String,
        isBackPin: Boolean,
    ) {
        ToastUtil.showShort(activity, "调用了qrSignData")
        activity.signetApi?.qrSignData(activity, msspID, pin, isBackPin) { p0 ->
            LogUtil.e("  SignDataResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "qrSignData",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun batchSignData(
        msspID: String,
        signJobList: ArrayList<String>,
        pin: String,
    ) {
        ToastUtil.showShort(activity, "调用了batchSign")
        activity.signetApi?.batchSignData(activity, msspID, signJobList, pin) { p0 ->
            LogUtil.e("   BatchSignResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "batchSignData",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun challengeSign(
        msspID: String,
        pin: String,
        isBackPin: Boolean,
    ) {
        ToastUtil.showShort(activity, "调用了challengeSign")
        activity.signetApi?.challengeSign(activity, msspID, pin, isBackPin) { p0 ->
            LogUtil.e(" SignDataResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "challengeSign",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun setSignPic(
        msspID: String,
        setSignImgType: String,
    ) {
        ToastUtil.showShort(activity, "调用了setSignPic")
        val status = SetSignImgType.values().find { it.name == setSignImgType }
        if (null != status) {
            activity.signetApi?.setSignPic(activity, msspID, status) { p0 ->
                LogUtil.e("  SignImageResult==" + Gson().toJson(p0).toString())
                agentWeb.jsAccessEntrace.quickCallJs(
                    "jsFunction",
                    "setSignPic",
                    Gson().toJson(p0).toString()
                )
            }
        } else {
            ToastUtil.showShort(activity, "未找到$setSignImgType")
        }

    }

    @JavascriptInterface
    fun getSignPic(
        msspID: String,
    ) {
        ToastUtil.showShort(activity, "调用了getSignPic")
        val singImageResult = activity.signetApi?.getSignPic(activity, msspID)
        LogUtil.e("  singImageResult==" + Gson().toJson(singImageResult).toString())
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "getSignPic",
            Gson().toJson(singImageResult).toString()
        )

    }

    @JavascriptInterface
    fun getUserList() {
        ToastUtil.showShort(activity, "调用了getUserList")
        val userListResult = activity.signetApi?.getUserList(activity)
        LogUtil.e("  userListResult==" + Gson().toJson(userListResult).toString())
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "getUserList",
            Gson().toJson(userListResult).toString()
        )
    }

    @JavascriptInterface
    fun getUserCert(msspID: String, certType: String) {
        ToastUtil.showShort(activity, "调用了getUserCert")
        val status = CertType.values().find { it.name == certType }
        if (null != status) {
            val getCertResult = activity.signetApi?.getUserCert(activity, msspID, status)
            LogUtil.e("  getCertResult==" + Gson().toJson(getCertResult).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "getUserCert",
                Gson().toJson(getCertResult).toString()
            )
        } else {
            ToastUtil.showShort(activity, "未找到$certType")
        }


    }

    @JavascriptInterface
    fun clearCert(msspID: String) {
        ToastUtil.showShort(activity, "调用了clearCert")
        val clearCertResult = activity.signetApi?.clearCert(activity, msspID)
        LogUtil.e("  clearCertResult==" + Gson().toJson(clearCertResult).toString())
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "clearCert",
            Gson().toJson(clearCertResult).toString()
        )
    }

    @JavascriptInterface
    fun setFingerStatus(
        msspID: String,
        pin: String,
        operType: String,
    ) {
        ToastUtil.showShort(activity, "调用了setFingerStatus")
        val status = SetFingerOperType.values().find { it.name == operType }
        if (null != status) {
            activity.signetApi?.setFingerStatus(activity, msspID, pin, status) { p0 ->
                LogUtil.e("   SignetBaseResult==" + Gson().toJson(p0).toString())
                agentWeb.jsAccessEntrace.quickCallJs(
                    "jsFunction",
                    "setFingerStatus",
                    Gson().toJson(p0).toString()
                )
            }
        } else {
            ToastUtil.showShort(activity, "未找到$operType")
        }

    }


    @JavascriptInterface
    fun getBioIDStatus(
        msspID: String,
    ) {
        ToastUtil.showShort(activity, "调用了getBioIDStatus")
        val bioStatusResult = activity.signetApi?.getBioIDStatus(activity, msspID)
        LogUtil.e("   bioStatusResult==" + Gson().toJson(bioStatusResult).toString())
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "getBioIDStatus",
            Gson().toJson(bioStatusResult).toString()
        )
    }


    @JavascriptInterface
    fun getUserState(msspID: String) {
        ToastUtil.showShort(activity, "调用了getUserState")
        activity.signetApi?.getUserState(activity, msspID) { p0 ->
            LogUtil.e("   UserStateResult==" + Gson().toJson(p0).toString())
            agentWeb.jsAccessEntrace.quickCallJs(
                "jsFunction",
                "getUserState",
                Gson().toJson(p0).toString()
            )
        }
    }

    @JavascriptInterface
    fun setShowPrivacy(isShow: Boolean) {
        ToastUtil.showShort(activity, "调用了setShowPrivacy")
        LogUtil.e("   isShow==$isShow")
        activity.signetApi?.setShowPrivacy(activity, isShow)

    }

    @JavascriptInterface
    fun analyzeCert(
        cert: String,
    ) {
        ToastUtil.showShort(activity, "调用了analyzeCert")
        val certResult = activity.signetApi?.analyzeCert(cert)
        LogUtil.e("   certResult==" + Gson().toJson(certResult).toString())
        agentWeb.jsAccessEntrace.quickCallJs(
            "jsFunction",
            "analyzeCert",
            Gson().toJson(certResult).toString()
        )
    }

}